const fs = require("fs");
const path = require("path");
const uuid = require("uuid/v1");
let config = require("../config");
let sequelize = require("../dao/sequelize");
const Op = require("sequelize").Op;

let mkdir = dir => {
  if (fs.existsSync(dir)) {
    return;
  } else {
    mkdir(path.dirname(dir));
    fs.mkdirSync(dir);
  }
};

exports.mkdir = mkdir;

exports.saveFile = async file => {
  mkdir(config.file_path);
  let newPath = `${config.file_path}/${uuid()}`;
  fs.copyFileSync(file.path, newPath);
  fs.unlinkSync(file.path);
  let file_model = sequelize.import("../dao/models/file");
  let file_model_result = await file_model.create({
    origin_name: file.name,
    size: file.size,
    path: newPath,
    type: file.type
  });
  return file_model_result;
};

exports.getFile = async id => {
  let file_model = sequelize.import("../dao/models/file");
  let file_model_result = await file_model.findOne({
    where: {
      id: {
        [Op.eq]: id
      }
    }
  });
  return file_model_result;
};
